package com.caffedev.ottollotto;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.ExpandableListAdapter;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;



public class OttollottoMain extends ListActivity {
	private final static String TAG = "OttollottoMain";

	private final String LOTTO_SITE_645 = "http://www.645lotto.net";
	private final String LAST_URL = "/resultall/dummy.asp";
	private final String LOTTO_SITE_KAISYU = "http://lotto.kaisyu.com/api?method=get&gno=";
	
	public static String GRWNO;
	public static String GRWDate;
	public static String FirstBall;
	public static String SecondBall;
	public static String ThirdBall;
	public static String FourthBall;
	public static String FifthBall;
	public static String SixthBall;
	public static String BonusBall;
	
	
	private static final String DATABASE_NAME = "base.db";
	private static final String DATABASE_DIR = "/data/data/com.caffedev.ottollotto/databases/";
	private static final String DATABASE_ASSETS = "database/base.db";
	private static final String TABLE_NAME = "mTable";
	
	public static DatabaseHelper mHelper;
	public static SQLiteDatabase mDb;
	public static Cursor mCursor;
	private myCursorAdapter ca;
	private ExpandableListAdapter mAdapter;
	
	
	
	
	public static final int ID=0;
	public static final int INDEX_GRWNO=1;
	public static final int INDEX_GRWDATE=2;
	public static final int INDEX_FIRSTBALL=3;
	public static final int INDEX_SECONDBALL=4;
	public static final int INDEX_THIRDBALL=5;
	public static final int INDEX_FOURTHBALL=6;
	public static final int INDEX_FIFTHBALL=7;
	public static final int INDEX_SIXTHBALL=8;
	public static final int INDEX_BONUSBALL=9;
	
	private static final String KEY_ID="_ID";
	private static final String KEY_GRWNO="grwno";
	private static final String KEY_GRWDATE="grwdate";
	private static final String KEY_FIRSTBALL="firstball";
	private static final String KEY_SECONDBALL="secondball";
	private static final String KEY_THIRDBALL="thirdball";
	private static final String KEY_FOURTHBALL="fourthball";
	private static final String KEY_FIFTHBALL="fifthball";
	private static final String KEY_SIXTHBALL="sixthball";
	private static final String KEY_BONUSBALL="bonusball";
	 
	
	// button to option menu
	private ImageButton option;
	
	//criteria ball number 
	private ImageView cb1;
	private ImageView cb2;
	private ImageView cb3;
	private ImageView cb4;
	private ImageView cb5;
	private ImageView cb6;
	
	private int[] criteriaBall={0,0,0,0,0,0};
	private int criteriaBall_index;
	
	private AlertDialog.Builder builder;
    private AlertDialog dialog;
	
	private int lastgrwno;
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.main);
		
		option = (ImageButton)findViewById(R.id.option);
		cb1 = (ImageView)findViewById(R.id.criteria_ball1);
		cb2 = (ImageView)findViewById(R.id.criteria_ball2);
		cb3 = (ImageView)findViewById(R.id.criteria_ball3);
		cb4 = (ImageView)findViewById(R.id.criteria_ball4);
		cb5 = (ImageView)findViewById(R.id.criteria_ball5);
		cb6 = (ImageView)findViewById(R.id.criteria_ball6);
		
	    option.setOnClickListener(listener);
	    cb1.setOnClickListener(listener);
	    cb2.setOnClickListener(listener);
	    cb3.setOnClickListener(listener);
	    cb4.setOnClickListener(listener);
	    cb5.setOnClickListener(listener);
	    cb6.setOnClickListener(listener);
	    
	  //  listview = (ListView)findViewById(android.R.id.list);
	    
	    //copyDatabase();
	    
	    
	    
	  //open database
	    mHelper = new DatabaseHelper(this);
	    mDb = mHelper.getWritableDatabase();
	    
	    String query = "select * from "+TABLE_NAME+" order by _id desc";
	    mCursor = mDb.rawQuery(query, null);
        mCursor.moveToFirst();
        startManagingCursor(mCursor);
        
        
        GRWNO = mCursor.getString(INDEX_GRWNO);
        ca = new myCursorAdapter(this,mCursor);
        setListAdapter(ca);
        //getListView().setOnItemClickListener(this);

        //smoothScrollByOffset(1);
        
        
        //check network state 
        
        
        //download and parse JSON object
	   
	   
	   //updateLotto();
	   
	   
	}
	private void updateLotto(){
		readJSONObject(LOTTO_SITE_645 + LAST_URL);
		   lastgrwno=	   Integer.parseInt(GRWNO);
		/*String query = "select GRWNO from "+TABLE_NAME;
		mCursor = mDb.rawQuery(query, null);
		mCursor.moveToLast();*/
		int no = Integer.parseInt(mCursor.getString(INDEX_GRWNO));
		
		if(lastgrwno == no){
			return;
		}
		
		else if((no - lastgrwno) == 1 )
				addNewItem();
			else 
			{
				for(int i = no+1; i <= lastgrwno;i++){
					readJSONObject2(LOTTO_SITE_KAISYU+i);
					addNewItem();
				}
		}
		ca.notifyDataSetChanged();
	}
private ImageView tView;

    private View.OnClickListener listener = new View.OnClickListener() {
    	
		public void onClick(View v) {
			
			switch(v.getId()){
			case  R.id.option:
				for(int i = 0; i<=5;i++)
					criteriaBall[i]=0;
				ca.notifyDataSetChanged();
				cb1.setBackgroundResource(R.drawable.red_round);
				cb2.setBackgroundResource(R.drawable.red_round);
				cb3.setBackgroundResource(R.drawable.red_round);
				cb4.setBackgroundResource(R.drawable.red_round);
				cb5.setBackgroundResource(R.drawable.red_round);
				cb6.setBackgroundResource(R.drawable.red_round);
				break;
			case R.id.criteria_ball1:
				criteriaBall_index = 0;
				tView = (ImageView)v;
				ballSelectDialog();
				break;
			case R.id.criteria_ball2:
				criteriaBall_index = 1;
				tView = (ImageView)v;
				ballSelectDialog();
				break;
			case R.id.criteria_ball3:
				criteriaBall_index = 2;
				tView = (ImageView)v;
				ballSelectDialog();
				break;
			case R.id.criteria_ball4:
				criteriaBall_index = 3;
				tView = (ImageView)v;
				ballSelectDialog();
				break;
			case R.id.criteria_ball5:
				criteriaBall_index = 4;
				tView = (ImageView)v;
				ballSelectDialog();
				break;
			case R.id.criteria_ball6:
				criteriaBall_index = 5;
				tView = (ImageView)v;
				ballSelectDialog();
				break;
			}
			
		}


	};
	
	
	
	private AdapterView.OnItemClickListener dialog_listener = new AdapterView.OnItemClickListener() {

		public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

			
			
			if(isInCriteria(position+1)){
				Toast.makeText(OttollottoMain.this,R.string.already_selected, Toast.LENGTH_SHORT).show();
			}else{
				criteriaBall[criteriaBall_index]=position+1;
				dialog.dismiss();
				tView.setBackgroundDrawable(v.getBackground());
				ca.getCursor().requery();
				ca.notifyDataSetChanged();
			}
			//Log.e(TAG,"position+1 : "+(position+1));
			/*for(int a = 0; a<=5;a++){
				Log.e(TAG,"criteriaBall : "+criteriaBall[a]);
			}*/
		}
	};
	
	//private Bitmap tmpBitmap;

	//////////////////////need to modify
	private boolean isInCriteria(int ball){
		for(int i=0; i<=5;i++){
			if(criteriaBall[i]==ball){
				return true;
			}
		}
		return false;

	}
	private void ballSelectDialog() {
		
		LinearLayout layout = (LinearLayout)View.inflate(OttollottoMain.this, R.layout.select_ball, null);
		//layout.setBackgroundColor(Color.WHITE);
		layout.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
		GridView grid = (GridView)layout.findViewById(R.id.gridView1);
		
		ImageAdapter adapter = new ImageAdapter(this);
		grid.setAdapter(adapter);
		
		
		grid.setOnItemClickListener(dialog_listener);
		
		builder = new AlertDialog.Builder(OttollottoMain.this);
		builder.setView(layout);

		dialog = builder.create();
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

		dialog.show();

	}

	private void addNewItem(){
		//mCursor.moveToLast();
		
		
		ContentValues arg = new ContentValues();
		
		
		arg.put(KEY_GRWNO, GRWNO);
		arg.put(KEY_GRWDATE, GRWDate);
		arg.put(KEY_FIRSTBALL, FirstBall);
		arg.put(KEY_SECONDBALL, SecondBall);
		arg.put(KEY_THIRDBALL, ThirdBall);
		arg.put(KEY_FOURTHBALL, FourthBall);
		arg.put(KEY_FIFTHBALL, FifthBall);
		arg.put(KEY_SIXTHBALL, SixthBall);
		arg.put(KEY_BONUSBALL, BonusBall);

		
		long rowId = mDb.insert(TABLE_NAME, null, arg);
	}
	private void copyDatabase(){

	   	File folder = new File(DATABASE_DIR);
	   	folder.mkdirs();
	   	
	   	File file = new File(DATABASE_DIR + DATABASE_NAME);
	       
	   	if(file.exists()){
	   		//Log.e(TAG,"database exists");
	   		return;
	       }
	       
	   	AssetManager assetManager = getResources().getAssets();
	   	try{
	   		InputStream is = assetManager.open(DATABASE_ASSETS, AssetManager.ACCESS_BUFFER);
	   		OutputStream out = new FileOutputStream(file);
	   		writeFile(is, out);
	   		out.close();
	   		is.close();
	   	}catch (Exception e){
	   		e.printStackTrace();
	   	}
	}
	
	private void writeFile(InputStream is, OutputStream os) throws IOException{
		int c = 0;
		while((c = is.read()) != -1)
			os.write(c);
		os.flush();
	}  
	private void readJSONObject2(String addr) {
        try{
        	//JSONArray ja = new JSONArray(DownloadHtml(addr));
        	//JSONObject jo = ja.getJSONObject(0);
        	JSONObject jo = new JSONObject(DownloadHtml(addr));
        	
        	JSONArray ja = jo.getJSONArray("nums");
        	
        	
        	GRWNO = jo.getString("gno");
        	GRWDate = jo.getString("gdate");
        	FirstBall = ja.getString(0);
        	SecondBall = ja.getString(1);
        	ThirdBall = ja.getString(2);
        	FourthBall = ja.getString(3);
        	FifthBall = ja.getString(4);
        	SixthBall = ja.getString(5);
        	BonusBall = jo.getString("bnum");

        	
        	
        }catch (JSONException e){
        	e.printStackTrace();
        }
		
	}
    private void readJSONObject(String addr) {
        try{
        	JSONArray ja = new JSONArray(DownloadHtml(addr));
        	JSONObject jo = ja.getJSONObject(0);
        	
        	GRWNO = jo.getString("GRWNO");
        	GRWDate = jo.getString("GRWDate");
        	FirstBall = jo.getString("FirstBall");
        	SecondBall = jo.getString("SecondBall");
        	ThirdBall = jo.getString("ThirdBall");
        	FourthBall = jo.getString("FourthBall");
        	FifthBall = jo.getString("FifthBall");
        	SixthBall = jo.getString("SixthBall");
        	BonusBall = jo.getString("BonusBall");
        	
        	
        }catch (JSONException e){
        	e.printStackTrace();
        }
		
	}

	private String DownloadHtml(String addr) {
		HttpGet httpget = new HttpGet(addr);
		DefaultHttpClient client = new DefaultHttpClient();
		StringBuilder html = new StringBuilder();
		String line=null;
		try {
			HttpResponse response = client.execute(httpget);
			BufferedReader br = new BufferedReader(new 
					InputStreamReader(response.getEntity().getContent()));
			for (;;) {
				line = br.readLine();
				if (line == null) break;
				html.append(line + '\n'); 
			}
			br.close();
		} 
		catch (Exception e) {
			e.printStackTrace();}
		
		
		return html.toString();
	}
    
	
	
	

	protected void onPause() {
		super.onPause();
	}
	protected void onRestart() {
		super.onRestart();
	}
	protected void onResume() {
		super.onResume();
	}
	protected void onStart() {
		super.onStart();
	}
	protected void onStop() {
		super.onStop();
	}
	protected void onDestroy(){
    	super.onDestroy(); 
    	mDb.close();
    	mHelper.close();
    }

	private int[] ball = {R.drawable.b1,R.drawable.b2,R.drawable.b3,R.drawable.b4,R.drawable.b5,
			R.drawable.b6,R.drawable.b7,R.drawable.b8,R.drawable.b9,R.drawable.b10,
			R.drawable.b11,R.drawable.b12,R.drawable.b13,R.drawable.b14,R.drawable.b15,
			R.drawable.b16,R.drawable.b17,R.drawable.b18,R.drawable.b19,R.drawable.b20,
			R.drawable.b21,R.drawable.b22,R.drawable.b23,R.drawable.b24,R.drawable.b25,
			R.drawable.b26,R.drawable.b27,R.drawable.b28,R.drawable.b29,R.drawable.b30,
			R.drawable.b31,R.drawable.b32,R.drawable.b33,R.drawable.b34,R.drawable.b35,
			R.drawable.b36,R.drawable.b37,R.drawable.b38,R.drawable.b39,R.drawable.b40,
			R.drawable.b41,R.drawable.b42,R.drawable.b43,R.drawable.b44,R.drawable.b45
	};
	////////////custom imageadapter
	public class ImageAdapter extends BaseAdapter{
		private Context mContext;
		
		public ImageAdapter(Context c){
			mContext = c;
		}
		public int getCount() {
			return ball.length;
		}
		public Object getItem(int position) {
			return ball[position];
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if(convertView == null){
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new GridView.LayoutParams(45,45));
				imageView.setAdjustViewBounds(false);
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			}else{
				imageView = (ImageView)convertView;
			}
			imageView.setBackgroundResource(ball[position]);
			return imageView;
		}
		
	}
	
	
	
	
	/////////////////////// custom CursorAdapter
	public class myCursorAdapter extends CursorAdapter{
		String ballShape = "b";//circle, 'c' to ring
		
    	public myCursorAdapter(Context ctx, Cursor cursor){
    		super(ctx, cursor,true);
    	}

		public void bindView(View view, Context context, Cursor cursor) {

			TextView grwno = (TextView)view.findViewById(R.id.grwno);
			ImageView ball1 = (ImageView)view.findViewById(R.id.image_ball1);
			ImageView ball2 = (ImageView)view.findViewById(R.id.image_ball2);
			ImageView ball3 = (ImageView)view.findViewById(R.id.image_ball3);
			ImageView ball4 = (ImageView)view.findViewById(R.id.image_ball4);
			ImageView ball5 = (ImageView)view.findViewById(R.id.image_ball5);
			ImageView ball6 = (ImageView)view.findViewById(R.id.image_ball6);
			ImageView bonus_ball = (ImageView)view.findViewById(R.id.image_bonus_ball);
			
			grwno.setText(cursor.getString(INDEX_GRWNO));//+getString(R.string.round));
	
			ball1.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_FIRSTBALL))) ? "c" : "b" ) +cursor.getString(INDEX_FIRSTBALL), "drawable", getPackageName()));
			ball2.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_SECONDBALL))) ? "c" : "b" ) +cursor.getString(INDEX_SECONDBALL), "drawable", getPackageName()));
			ball3.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_THIRDBALL))) ? "c" : "b" ) +cursor.getString(INDEX_THIRDBALL), "drawable", getPackageName()));
			ball4.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_FOURTHBALL))) ? "c" : "b" ) +cursor.getString(INDEX_FOURTHBALL), "drawable", getPackageName()));
			ball5.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_FIFTHBALL))) ? "c" : "b" ) +cursor.getString(INDEX_FIFTHBALL), "drawable", getPackageName()));
			ball6.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_SIXTHBALL))) ? "c" : "b" ) +cursor.getString(INDEX_SIXTHBALL), "drawable", getPackageName()));
			bonus_ball.setBackgroundResource(getResources().getIdentifier((isInCriteria(Integer.valueOf(cursor.getString(INDEX_BONUSBALL))) ? "c" : "b" )+cursor.getString(INDEX_BONUSBALL), "drawable", getPackageName()));
			
		}

		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			//LayoutInflater inflater = ((Activity)this).getLayoutInflater();
			LayoutInflater inflater = LayoutInflater.from(context);
			View row = (View)inflater.inflate(R.layout.row, parent,false);


			return row;
		}
    }
	
	
	
}
